package com.whj.internalcommon.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.whj.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: wanghaijun
 * @Date: 2022/12/31 - 12 - 31 - 15:30 
 * @Description: 生成token验证token
 */

public class JwtUtils {

    //盐
    private static final String SIGN="WHJ@QQ123";

    private static final String JWT_KEY_PHONE="phone";

    //1 表示乘客，0表示司机  加入身份标识符来确保身份
    private static final String JWT_KEY_IDENTITY ="identity";

    private static final String JWT_TOKEN_TYPE="tokenType";

    private static final String JWT_TOKEN_TIME="tokenTime";

    //生成token
    public static String generatorToken(String passengerPhone,String identity,String tokenType){

        Map<String,String> map =new HashMap<>();
        map.put(JWT_KEY_PHONE,passengerPhone);
        map.put(JWT_KEY_IDENTITY,identity);
        map.put(JWT_TOKEN_TYPE,tokenType);

        //设置token的创建时间防止数据相同生成的token是相同的 加入时间戳
        map.put(JWT_TOKEN_TIME,Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();
        //整合map lambda表达式
        map.forEach(
                (k,v)->{
                        builder.withClaim(k,v);
                });

        //生成token
        String token = builder.sign(Algorithm.HMAC256(SIGN));
        return token;
    }
    //解析token
    public static TokenResult parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);

        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();

        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    /**
     * 校验token主要判断token是否异常
     * @param token
     * @return
     */
    public static TokenResult checkToken(String token){
        TokenResult tokenResult=null;
        try {
            tokenResult = JwtUtils.parseToken(token);
        } catch (Exception e) {

        }
        return tokenResult;
    }
    public static void main(String[] args) {

        String token = generatorToken("14760186137","1","accessToken");
        System.out.println("token = " + token);
        TokenResult tokenResult = parseToken(token);
        System.out.println("解析后token的包含的值 = " + tokenResult.getIdentity()+" "+tokenResult.getPhone());
    }
}
